import logging

import hashlib
import time
import uuid
import datetime
import requests
import redis
#from lxml import etree
import json

from utils.formatutils import get_body

r = redis.Redis(host='localhost', port=6379, decode_responses=True)  # host是redis主机，需要redis服务端和客户端都启动 redis默认端口是6379

salt = "JXU2NDkyJXU2MjUzJXU3Qjk3JXU2MjUz"


class ApiDecoder:
    def __init__(self):
        pass


class BaseSpider:
    def __init__(self, addr, port, username, password):
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36",
            "Referer": "https://www.guokr.com/ask/highlight/"
        }
        self.addr = addr
        self.port = port
        self.login(username, password)
    
    def get_html(self, request):
        return request.content.decode()
    
    def login(self, username, password):
        """
        登陆
        :return:
        """
        data = {
            "time": int(time.time()),
            "params": {
                "name": username,
                "password": password
            },
            "appInfo": {
                "version": "V1.0"
            }
        }
        request = requests.post("http://{}:{}/login?active=login".format(self.addr, self.port), headers=self.headers, json=data)
        html_str = self.get_html(request)
        body = json.loads(html_str)
        uid, token = str(body.get("data").get("token")).split("==")
        self.uid = uid
        self.token = token[4:]
    
    def get_reqbody(self, active, **kwargs):
        body = {}
        token = self.uid
        if token is None:
            return None
        reqtime = int(time.time())
        body["uid"] = self.token
        body["salt"] = salt
        body["time"] = reqtime
        body["params"] = kwargs
        body["apiName"] = active
        body_str = ""
        body_list = sorted(body.items(), key=lambda x: x[0], reverse=True)
        for param in body_list:
            body_str += "{}={}&".format(param[0], str(param[1]))
        body_str = body_str[:-1]
        signature = hashlib.sha256(body_str.encode()).hexdigest()
        print(body_str)
        print(signature)
        
        
        reqbody = {
            "time": reqtime,
            "uid": self.uid,
            "params": kwargs,
            "appInfo": {
                "version": "V1.0"
            },
            "signature": signature
        }
        return reqbody
    
    def run(self, app, active, **kwargs):
        # if not all([kwargs]):
        #     kwargs["keep"] = 1
        reqbody = self.get_reqbody(active, **kwargs)
        logging.info("--"*50)
        print("==" * 50)
        print(json.dumps(reqbody))
        if reqbody is None:
            print("token is None")
        print("--" * 50)
        print("{}:{}/{}?active={}".format(self.addr, self.port, app, active))
        print("--" * 50)
        request = requests.post("http://{}:{}/{}?active={}".format(self.addr, self.port, app, active),
                                headers=self.headers, json=reqbody)
        html_str = self.get_html(request)
        print(json.loads(html_str))
        print("==" * 50)



if __name__ == '__main__':
    spider = BaseSpider("59.110.217.232", 8000, "zhuliye", "123456")
    # spider.run("notice", "notice_check", user_id=1,notice_id=1)
    # spider.run("login", "login", name="mei",password="123456")
    # spider.run("process", "check_process", process_id=28)
    # spider.run("home_page", "unfinished_task_list", user_id=6, query_str="测试",isAll=True)
    # spider.run("home_page", "last_notice", user_id=1)
    # spider.run("project", "project_task_add", title="asd as",task_describe="352413541",star_time="2017-09-18 18:39:01",end_time="2018-09-18 18:39:01",reciverlist_id=1,task_push_user_id=2, task_project_id=104)
    # spider.run("project", "project_circle_add", user_id=1,report_content="增加",project_id=104)
    # spider.run("project", "my_project_message", user_id=1)
    # spider.run("project", "project_message", project_id=104)
    # spider.run("project", "project_list", user_id=1,isAll=False,page=1,limit=3,query=None)
    # spider.run("home_page", "unfinished_task_num", user_id=1,isAll=False,page=1,limit=3)
    # spider.run("training", "train_list", user_id=33, status_id=34,isAll=True)
    # spider.run("training", "classify_inquire", status_id=33, isAll=True)
    # spider.run("training", "train_check", id=2, isAll=True)
    # spider.run("training", "my_read", user_id=1, isAll=True)
    # spider.run("task", "speed_setting", task_id=55, user_id=1,comment="23rsae",progress_speed=0.72)
    # spider.run("task", "speed_info", task_id=55, isAll=True)
    # spider.run("task", "mytasks", user_id=1,isAll=True)
    # spider.run("task", "subordinates_task", user_id=1, isAll=True)
    # spider.run("task", "mytasks", user_id=1, priority_level=0, status_id=5, isAll=True)
    # spider.run("task", "subordinates_task", user_id=1, priority_level=0, status_id=5, isAll=True)
    # spider.run("task", "task_details", task_id=55)
    # spider.run("task", "task_add", title="标题",task_describe="描述",star_time="2018-12-23 18:18:18",end_time="2019-12-23 18:18:18",reciverlist_id=2,task_push_user_id=1)
    # spider.run("process", "examine_process", user_id=2,process_id=145,status_id=25,advice="继续啊 啊努力",next_user_id=3)
    # spider.run("friend", "all_friend", user_id=3)
    # spider.run("project", "my_project_message", user_id=3)
    # spider.run("project", "project_circle_list", project_id=104, user_id=1, query_str="增加",isAll=True)
    # spider.run("project", "project_task", project_id=104, status_id=3,isAll=True)
    # spider.run("notice", "notice_check", user_id=1, notice_id=1,page=2,limit=3)
    # spider.run("notice", "notice_list", user_id=1,query_str="1111",isAll=True)
    # spider.run("achieve", "performance_rank", user_id=1,isAll=False,page=1,limit=3)
    # spider.run("friend", "all_friend", user_id=1)
    # spider.run("friend", "check_friend", user_id=1,isAll=True)
    # spider.run("user", "check_message", user_id=1,isAll=True)
    # spider.run("organization", "dept_tree", user_id=1,isAll=True)
    # spider.run("organization", "dept_list", user_id=1, query_str="财务",isAll=True)
    # spider.run("process", "create_holiday",next_user_id=1,process_user_id=2,start_time="2018-12-23 18:18:18",end_time="2018-12-23 18:18:18",deeply_id=23,process_des="请假",process_name="啦啦啦啦",config_id=1,leave_days=4,holiday_id=40)
    # spider.run("process", "create_go_out", next_user_id=1,process_user_id=2,start_time="2018-12-23 18:18:18",end_time="2018-12-23 18:18:18",deeply_id=22,process_des="哪里",process_name="我要外出啦",config_id=3, address="北大街", leave_time=9)
    # spider.run("process", "create_resign", next_user_id=1,process_user_id=2,start_time="2018-12-23 18:18:18",end_time="2018-12-23 18:18:18",deeply_id=24,process_des="shanku[paolu",process_name="我要来自惠",config_id=2, is_finish=1, nofinish="交接完毕",hand_user=1)
    # spider.run("process", "create_bursement",next_user_id=1,process_user_id=2,deeply_id=22,process_des="mysql325rw",process_name="闪酷跑路",config_id=4,name="相关客户",bursedetails=[{"produce_time": "2018-03-08 11:11:11","subject_id": 18,"descript": "这是一段描述","invoices": 3,"detailmoney": 2.5},{"produce_time": "2018-03-08 11:11:11","subject_id": 19,"descript": "这是一段描述","invoices": 3,"detailmoney": 2.5}])
    # spider.run("process", "create_purchase",next_user_id=1,process_user_id=2,deeply_id=22,process_des="有US哦啊哈三",process_name="有座山啊",config_id=5,name="相关客户",purchasedetails=[{"goods_name": "物品名称","goods_number": "申请采购","detailmoney": 2.1,"invoices": 2},{"goods_name": "物品名称","goods_number": "申请采购","detailmoney": 2.1,"invoices": 2}])
    # spider.run("process", "create_free_stop",next_user_id=1,process_user_id=2,deeply_id=23,process_des="周杰伦",process_name="双节棍",config_id=6,license="陕西C",consume_money=30,derate_level=51)
    # spider.run("process", "create_special_car",next_user_id=1,process_user_id=2,start_time="2018-12-23 18:18:18",end_time="2018-12-23 18:18:18",deeply_id=22,process_des="哈哈哈哈",process_name="夸一组",config_id=7,license="陕西C")
    # spider.run("user", "check_message", user_id=35)
    # spider.run("process", "my_unreviewed", user_id=1,isAll=True)
    # spider.run("process", "my_reviewed", user_id=1,isAll=True)
    # spider.run("process", "my_apply", user_id=2,isAll=True)
    # spider.run("process", "process_list", user_id=30, isAll=False, limit=3, page=2)
    # spider.run("project", "project_list", user_id=1, limit=1, page=8)
    # spider.run("note", "subordinates_note_filter", user_id=1,catalog_id=2, limit=2, page=3)
    # spider.run("note", "subordinates_note_list", user_id=1, catalog_id=1, is_read=1, isAll=True)
    # spider.run("note", "check_note", note_id=90, isAll=True)
    # spider.run("note", "my_note_filter", user_id=1, catalog_id=1, isAll=True)
    # spider.run("note", "my_note_list", user_id=1, catalog_id=1, receiver_to_me=1,isAll=True)
    # spider.run("project", "project_message", user_id=1, project_id=1, limit=1, page=8)
    spider.run("achieve", "all_performance_classify", user_id=1)
    # spider.run("achieve", "performance_appraisal", user_id=31, isAll=False, limit=3, page=2)
    # spider.run("achieve", "add_or_sub_performance", user_id=1, add_or_sub=0, isAll=False, limit=3, page=2)
    #spider.run("home_page", "my_unreviewed_num", user_id=1,isALL=True)
    # spider.run("train", "classify", user_id=2,isAll=True)
    # spider.run("organization", "dept_people", dept_id=1,isAll=True)
    # spider.run("organization", "dept_list", user_id=2,isAll=True)
    # spider.run("achieve", "subordinates_add_or_sub", user_id=2, performance_id=2,subordinates_id=3)
    # spider.run("achieve", "other_record",user_id=1, isAll=True)
    # spider.run("achieve", "my_record",user_id=1, isAll=True)
    # spider.run("achieve", "performance_edit",id=3, add_or_sub=0,status_id=31,content="码云",record=3,is_active=1)
    # spider.run("achieve", "performance_create", add_or_sub=0,status_id=31,content="码云",record=3,is_active=1)
    # spider.run("achieve", "performance_filter", add_or_sub=0,status_id=31,isAll=True)
    # spider.run("id_name", "id_name", user_id=28)
    # spider.run("send_img", "receive_img", user_id=1)s
    # spider.run("send_img", "upload_img",img_name="1.jpg",id=35,name="user_img",img_base64="")
    # spider.run("send_img", "upload_img",img_name="图片名字",img_base64="")
    # spider.run("process", "examine_process", process_id=28,user_id=1,status_name="已批准",advice="眷侣",next_user_id=2)
    # spider.run("process", "check_process", process_id=28)
    # spider.run("achieve", "subordinates_add_or_sub",modify_time=datetime.datetime.now().strftime('%Y:%m:%d %H:%M:%S'),task_id=1,comment="我来发表一条评论",user_id=1,progress_speed=0.99)
    # spider.run("task", "task_details",title=9999999,status_id=1,task_describe="这是一段描述",star_time="2017-09-18 18:39:01",end_time="2018-09-18 18:39:01",reciverlist_id=2,task_push_user_id=3,modify_time="now()",publish_time="now()",task_project_id=15)
    # spider.run("task", "all_task_classify",user_id=1)
    # spider.run("note", "all_note_classify", user_id=1)
